package boundarys;

import java.awt.Label;
import java.awt.List;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

import ccrm.BoundryControl;
import controllers.DeleteProductController;
import controllers.ManageCategoriesController;
import controllers.ManageTypesController;
import entitys.Category;
import entitys.Reply;
import entitys.Type;
import enums.Command;
import enums.Result;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class ManageCategoriesGUI extends AbstractGUI {

	/**
	 * Manage categories frame
	 */
	private JFrame frmmanageCategories;
	/**
	 * List of product categories to store the result from server
	 */
	ArrayList<Category> arr=null;
	/**
	 * List of product categories to add to the frame list
	 */
	private List productsCategoryList;
	/**
	 * Labels
	 */
	private Label searchLabel;
	private Label categoryNameLabel;
	private Label categoriesindbLabel;
	/**
	 * Buttons
	 */
	private JButton BackBtn;
	private JButton ConfirmBtn;
	private JButton AddCategoryBtn;
	private JButton RefreshBtn;
	private JButton ClearBtn;
	private JButton EditCategoryBtn;
	private JButton DeleteCategoryBtn;
	/**
	 * category text field
	 */
	private JTextField textField;
	/**
	 * search text field
	 */
	private JTextField searchTextField;

	/**
	 * Constructor
	 */
	public ManageCategoriesGUI() {
		initialize();
		initGUI(frmmanageCategories);

	}
	
	/**
	 * 
	 * @return product categories list
	 */
	public List getProductsCategoryList() {
		return productsCategoryList;
	}
	
	/**
	 * sets the product category list
	 * @param productsCategoryList
	 */
	public void setProductsCategoryList(List productsCategoryList) {
		this.productsCategoryList = productsCategoryList;
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frmmanageCategories = new JFrame();
		/**
		 * Mouse Listener
		 * Whenever frame is clicked it deselects the selected item in list
		 */
		frmmanageCategories.getContentPane().addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				productsCategoryList.deselect(productsCategoryList.getSelectedIndex());	
			}
		});
		frmmanageCategories.setTitle("...Manage Product Category/Type>Manage Categories");
		frmmanageCategories.setResizable(false);
		frmmanageCategories.setBounds(100, 100, 466, 426);
		frmmanageCategories.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		
		frmmanageCategories.getContentPane().setLayout(null);
		
		productsCategoryList = new List();
		/**
		 * Mouse Listener
		 * Whenever product category is selected it sets the text field text to the product type name
		 */
		productsCategoryList.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				String tmp = (String)productsCategoryList.getSelectedItem();
				textField.setText(tmp.substring(tmp.indexOf(" ")).trim());
			}
		});

		productsCategoryList.setMultipleSelections(false);
		productsCategoryList.setBounds(35, 75, 219, 221);
		frmmanageCategories.getContentPane().add(productsCategoryList);
		
		/**
		 * sends the server a request to get product categories list
		 */
		ManageCategoriesController.getProductCategories();
		
		categoriesindbLabel = new Label("Product categories in db");
		categoriesindbLabel.setBounds(35, 47, 203, 22);
		frmmanageCategories.getContentPane().add(categoriesindbLabel);
		
		categoryNameLabel = new Label("Category name:");
		categoryNameLabel.setBounds(9, 314, 90, 22);
		frmmanageCategories.getContentPane().add(categoryNameLabel);
		
		JButton RefreshBtn = new JButton("Refresh");
		/**
		 * Action Listener for Refresh Button
		 * Gets the updated product types list and shows it in the list
		 */
		RefreshBtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(BoundryControl.GUIArr.size()==getIndex()+1)
				{
					ManageCategoriesController.getProductCategories();
				}
			}
		});
		RefreshBtn.setBounds(286, 237, 137, 43);
		frmmanageCategories.getContentPane().add(RefreshBtn);
		
		textField = new JTextField();
		textField.setBounds(101, 314, 153, 22);
		frmmanageCategories.getContentPane().add(textField);
		
		BackBtn = new JButton("Back");
		/**
		 * Action Listener for Back Button
		 * Goes back to previous frame
		 */
		BackBtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				goBack();
			}
		});
		BackBtn.setBounds(9, 361, 89, 23);
		frmmanageCategories.getContentPane().add(BackBtn);
		
		AddCategoryBtn = new JButton("Add Category");
		/**
		 * Action Listener for Add Category Button
		 * if the category already exists or the name is empty it does not add 
		 * else adds new category to list and database
		 */
		AddCategoryBtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(BoundryControl.GUIArr.size()==getIndex()+1)
				{
					if(productsCategoryList.getSelectedItem()!=null)
					{
						JOptionPane.showMessageDialog(frmmanageCategories, "Unable to add an existing category", "CCRM Manage Categories", JOptionPane.ERROR_MESSAGE);
					}
					else if(textField.getText().equals(""))
					{
						JOptionPane.showMessageDialog(frmmanageCategories, "Please enter a category name", "CCRM Manage Categories", JOptionPane.ERROR_MESSAGE);
					}
					else if(exists(productsCategoryList, textField.getText()))
					{
						JOptionPane.showMessageDialog(frmmanageCategories, "Unable to add an existing category", "CCRM Manage Categories", JOptionPane.ERROR_MESSAGE);
					}
					else
					{
						ManageCategoriesController.addCategory(textField.getText(), getProductsCategoryList().getItemCount());//send request to add category
					}
				}
			}

		});
		AddCategoryBtn.setBounds(286, 75, 137, 43);
		frmmanageCategories.getContentPane().add(AddCategoryBtn);
		
		EditCategoryBtn = new JButton("Edit Category");
		/**
		 * Action Listener for Edit Category Button
		 * if the category is not selected or the new type name is the same or empty or already exists it shows corresponding message 
		 * else adds changes category name in list and updates the database
		 */
		EditCategoryBtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(BoundryControl.GUIArr.size()==getIndex()+1)
				{
					String selected = (String)productsCategoryList.getSelectedItem();
					
					if(productsCategoryList.getSelectedItem() == null)
						JOptionPane.showMessageDialog(frmmanageCategories, "Select a category to edit", "CCRM Manage Categories", JOptionPane.ERROR_MESSAGE);
					else{
						String newcategory = JOptionPane.showInputDialog(frmmanageCategories, "Enter new name for selected category:", "CCRM>Edit Category", JOptionPane.OK_CANCEL_OPTION);
						int cid = Integer.parseInt(selected.substring(1,selected.indexOf(" ")).trim());
						if(newcategory.equals(selected.substring(selected.indexOf(" ")).trim()))
							JOptionPane.showMessageDialog(frmmanageCategories, "New category name must be different", "CCRM Manage Categories", JOptionPane.ERROR_MESSAGE);
						else if(exists(productsCategoryList, newcategory))
							JOptionPane.showMessageDialog(frmmanageCategories, "Product category already exists", "CCRM Manage Categories", JOptionPane.ERROR_MESSAGE);
						else if(newcategory.equals(""))
							JOptionPane.showMessageDialog(frmmanageCategories, "New category name must be not empty", "CCRM Manage Categories", JOptionPane.ERROR_MESSAGE);	
						else
							ManageCategoriesController.editCategory(newcategory,cid);
					}
				}
			}
		});
		EditCategoryBtn.setBounds(286, 129, 137, 43);
		frmmanageCategories.getContentPane().add(EditCategoryBtn);
		
		DeleteCategoryBtn = new JButton("Delete Category");
		/**
		 * Action Listener for Delete Category Button
		 * if the category is not selected it shows corresponding message 
		 * else delete category name from list and updates the database
		 */
		DeleteCategoryBtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(BoundryControl.GUIArr.size()==getIndex()+1)
				{
					if(productsCategoryList.getSelectedItem() == null)
						JOptionPane.showMessageDialog(frmmanageCategories, "Select a category to delete", "CCRM Manage Categories", JOptionPane.ERROR_MESSAGE);
					else
					{
						String c = (String)productsCategoryList.getSelectedItem();
						int cid = Integer.parseInt(c.substring(1,c.indexOf(" ")).trim());
						ManageCategoriesController.deleteCategory((String)productsCategoryList.getSelectedItem(), cid);
					}
				}
			}
		});
		DeleteCategoryBtn.setBounds(286, 183, 137, 43);
		frmmanageCategories.getContentPane().add(DeleteCategoryBtn);
	 	
		ClearBtn = new JButton("Clear");
		/**
		 * Action Listener for Clear Button
		 * Clears the category text field
		 */
		ClearBtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(BoundryControl.GUIArr.size()==getIndex()+1)
				{
					textField.setText("");
				}
			}
		});
		ClearBtn.setBounds(270, 313, 89, 23);
		frmmanageCategories.getContentPane().add(ClearBtn);
		
		searchLabel = new Label("Search categories:");
		searchLabel.setBounds(35, 10, 106, 22);
		frmmanageCategories.getContentPane().add(searchLabel);
		
		searchTextField = new JTextField();
		/**
		 * Key Listener for search text field
		 * Whenever key is released it updates the category list by showing the names that contains the string that was typed
		 */
		searchTextField.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent e) {
				if(searchTextField.getText().isEmpty())
					ManageCategoriesController.getProductCategories();
				else
					ManageCategoriesController.getProductCategories(searchTextField.getText());
			}
		});
		searchTextField.setColumns(10);
		searchTextField.setBounds(165, 10, 137, 22);
		frmmanageCategories.getContentPane().add(searchTextField);
		
		
		frmmanageCategories.setVisible(true);
	}

	/**
	 * 
	 * @param l
	 * @param text
	 * @return whether text exists in the list l
	 */
	public boolean exists(List l, String text) {
		for(int i=0;i<l.getItemCount();i++)
		{
			String tmp = (String)l.getItem(i);
			if(text.equals(tmp.substring(tmp.indexOf(" ")).trim()))
				return true;
		}
		return false;
	}
	
	/**
	 * Reply from server
	 * Does the right action according to the command that was sent from the controller
	 */
	@Override
	public void getReply(Object r) {
		// TODO Auto-generated method stub
		if(((Reply)r).command.equals(Command.GET_PRODUCT_CATEGORIES)) //if GET_PRODUCTS reply is received
		{
			arr =(ArrayList<Category>) ((Reply)r).result;
			productsCategoryList.removeAll();
			
			for(int i=0;i<arr.size();i++)
			{
				productsCategoryList.add(arr.get(i).toString());
			}
		}
		
		else if(((Reply)r).command.equals(Command.GET_PRODUCT_CATEGORIES_WITH_PREFIX)) //if GET_PRODUCTS reply is received
		{
			arr =(ArrayList<Category>) ((Reply)r).result;
			productsCategoryList.removeAll();
			
			if(!arr.isEmpty())
			{
				for(int i=0;i<arr.size();i++)
				{
					productsCategoryList.add(arr.get(i).toString());
				}
			}
		}
		
		else if(((Reply)r).command.equals(Command.ADD_CATEGORY))
		{
			if (((Reply)r).result.equals(Result.OK))
			{
				System.out.println("Category added successfully!");
				JOptionPane.showMessageDialog(frmmanageCategories, "Category added successfully", "CCRM Manage Categories", JOptionPane.INFORMATION_MESSAGE);
			}
			ManageCategoriesController.getProductCategories();
			
		}
		
		else if(((Reply)r).command.equals(Command.EDIT_CATEGORY))
		{
			if (((Reply)r).result.equals(Result.OK))
			{
				System.out.println("Category updated successfully!");
				JOptionPane.showMessageDialog(frmmanageCategories, "Category updated successfully", "CCRM Manage Categories", JOptionPane.INFORMATION_MESSAGE);
			}
			ManageCategoriesController.getProductCategories();
			
		}
		
		else if(((Reply)r).command.equals(Command.DELETE_CATEGORY))
		{
			if (((Reply)r).result.equals(Result.OK))
			{
				System.out.println("Category deleted successfully!");
				JOptionPane.showMessageDialog(frmmanageCategories, "Category deleted successfully", "CCRM Manage Categories", JOptionPane.INFORMATION_MESSAGE);
			}
			ManageCategoriesController.getProductCategories();
			
		}
		
	}
}
